import React, { Component } from 'react'
import { StatusBar, Alert, Modal, ActivityIndicator, BackHandler, ScrollView, Text, View, KeyboardAvoidingView } from 'react-native'
import { Button, TextInput } from '../Components'
import { connect } from 'react-redux'

import AppConfig from '../Config/AppConfig'
const domain = AppConfig.domain

// Styles
import styles from './Styles/PasswordScreenStyle'

class PasswordScreen extends Component {
  static navigationOptions = {
    title: '修改密码'
  }
  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false,
      oldPassword: '',
      newPassword: '',
      rePassword: '',
    }
  }
  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  _onSubmit = () => {
    if(this.state.oldPassword.length < 3) {
      Alert.alert('旧密码格式错误')
      return
    } else if (this.state.newPassword.length < 6) {
      Alert.alert('密码最少6位')
      return
    } else if (this.state.newPassword !== this.state.rePassword) {
      Alert.alert('两次密码不一致')
      return
    } else {
      this.setState({modalVisible:true})
      this._resetPassword()
    }
  }
  _resetPassword() {
    let url = domain + '/api/user/password'
    return fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': this.props.token
      },
      body: JSON.stringify({
        old_password: this.state.oldPassword,
        new_password: this.state.newPassword
      })
    }).then((response) => response.json())
      .then((responseJson) => {
        this.setState({modalVisible:false})
        if(responseJson.code == 1) {
          Alert.alert('密码修改成功')
          this.props.navigation.goBack()
        } else {
          Alert.alert(responseJson.msg)
        }
      })
      .catch((error) => {
        this.setState({modalVisible:false})
        Alert.alert('密码修改失败')
      })
  }
  render () {
    return (
      <ScrollView style={styles.container}>
        <StatusBar translucent={false} barStyle='dark-content' backgroundColor='white' />
        <KeyboardAvoidingView behavior='position' style={styles.form}>
          <Text>旧密码</Text>
          <TextInput secureTextEntry
            style={styles.input}
            placeholder='请输入原始密码'
            onChangeText={(value)=>this.setState({oldPassword:value})} />
          <Text>新密码</Text>
          <TextInput secureTextEntry
            style={styles.input}
            placeholder='请输入新密码，至少6位'
            onChangeText={(value)=>this.setState({newPassword:value})} />
          <Text>重复密码</Text>
          <TextInput secureTextEntry
            style={styles.input}
            placeholder='请重复输入新密码'
            onChangeText={(value)=>this.setState({rePassword:value})} />
          <Button onPress={this._onSubmit} title='保存' />
        </KeyboardAvoidingView>
        <Modal
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={()=>null}>
          <View style={styles.loadingModal}>
            <View style={styles.loadingModalContainer}>
              <ActivityIndicator color='rgba(255,255,255,0.85)' />
              <Text style={styles.loadingModalTitle}>请稍后...</Text>
            </View>
          </View>
        </Modal>
      </ScrollView>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.user.payload.token
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(PasswordScreen)
